package com.hdoit.ares.web.cust.wechat;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.ares.logical.acc.model.WithdrawParam;
import com.hdoit.ares.logical.acc.service.IAccountInfoService;
import com.hdoit.ares.logical.acc.service.IIncomeInfoService;
import com.hdoit.ares.logical.acc.service.IWithdrawParamService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.cust.service.ICustomerService;
import com.hdoit.ares.logical.viewmodel.cust.TeamShareCustomer;
import com.hdoit.ares.selfcommon.enums.AresManageContainer;
import com.hdoit.ares.selfcommon.enums.cust.CusttomerIDtype;
import com.hdoit.ares.selfcommon.utils.AddMonthUtil;
import com.hdoit.ares.selfcommon.utils.realNameUtil;
import com.hdoit.ares.web.cbase.busutils.CustomerQrcodeUtil;
import com.tennetcn.common.enums.pub.YesOrNo;
import com.tennetcn.common.message.WechatLoginModel;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.JsonUtils;
import com.tennetcn.component.wechat.BaseWechat;
import com.tennetcn.component.wechat.WechatManager;
import com.tennetcn.web.cbase.WechatAuthPassport;


@Controller
@RequestMapping(value="/wechat/cust/personCenter/")
public class PersonCenterWechat extends BaseWechat{

	@Override
	public String getRoutePath() {
		return "areas/wechat/cust/personCenter/";
	}
	
	
	private ICustomerService customerService;
	private IAccountInfoService accountInfoService;
	private CustomerQrcodeUtil customerQrcodeUtil;
	private IIncomeInfoService incomeInfoService;
	private IWithdrawParamService withdrawParamService;
	
	public ICustomerService getCustomerService() {
		return customerService;
	}
	@Resource
	public void setCustomerService(ICustomerService customerService) {
		this.customerService = customerService;
	}
	
	public IAccountInfoService getAccountInfoService() {
		return accountInfoService;
	}
	@Resource
	public void setAccountInfoService(IAccountInfoService accountInfoService) {
		this.accountInfoService = accountInfoService;
	}
	
	public CustomerQrcodeUtil getCustomerQrcodeUtil() {
		return customerQrcodeUtil;
	}	
	@Resource
	public void setCustomerQrcodeUtil(CustomerQrcodeUtil customerQrcodeUtil) {
		this.customerQrcodeUtil = customerQrcodeUtil;
	}
	
	public IIncomeInfoService getIncomeInfoService() {
		return incomeInfoService;
	}
	@Resource
	public void setIncomeInfoService(IIncomeInfoService incomeInfoService) {
		this.incomeInfoService = incomeInfoService;
	}

	public IWithdrawParamService getWithdrawParamService() {
		return withdrawParamService;
	}
	@Resource
	public void setWithdrawParamService(IWithdrawParamService withdrawParamService) {
		this.withdrawParamService = withdrawParamService;
	}


	private final String boundPhoneViewName = "boundPhone";
	private final String indexViewName="index";
	private final String shareCodeViewName="shareCode";
	private final String myTeamViewName="myTeam";
	private final String teamContentViewNameString = "teamContent";
	private final String teamShareViewName="teamShare";
	private final String searchTeamViewName = "searchTeam";
	private final String currentTeamShareViewName="currentTeamShare";
	private final String getCustomerInfoViewName="getCustomerInfo";
	private final String shareCodeQrViewName="shareCodeQr";
	private final String shareSignatureViewName="shareSignature";
	private final String personDetailedViewName="personDetailed";
	private final String joinMakerViewName="joinMaker";
	private final String realNameViewName="realName";
	private final String torealNameViewName="torealName";

	@RequestMapping(value = indexViewName, method = { RequestMethod.GET })
	public String index(Model model){
		WechatLoginModel loginModel=wechatSession.getCurrentLogin();
		model.addAttribute("loginModel", loginModel);
		
		updateLoginModel();
		
		Customer customer = customerService.queryModel(loginModel.getUserId());
		
		//如果登录人的手机号为空的话，返回到注册页面
		if(StringUtils.isEmpty(customer.getPhone())){
			model.addAttribute("customer", customer); 
			return view(boundPhoneViewName);
		}
		
		model.addAttribute("customer", customer);
	
		Double allGoldenBean = accountInfoService.queryGoldBean(customer.getId());
		Double allIncome = incomeInfoService.queryIncomeBalance(customer.getId());
		
		model.addAttribute("allGoldenBean", allGoldenBean);
		model.addAttribute("allIncome",allIncome);
		return view(indexViewName);
	}
	
	@RequestMapping(value = joinMakerViewName, method = { RequestMethod.GET })
	public String joinMaker(Model model){
		return view(joinMakerViewName);
	}
	
	@RequestMapping(value = shareCodeViewName, method = { RequestMethod.GET })
	public String shareCode(Model model){
		return view(shareCodeViewName);
	}
	
	@WechatAuthPassport
	@RequestMapping(value =shareCodeQrViewName, method = { RequestMethod.GET })
	public String shareCodeQr(Model model,String shareCode){
		String sceneCode=shareCode;
		//二维码对象
		Customer qrCustomer=null;
		if(StringUtils.isEmpty(shareCode)){
			WechatLoginModel loginModel=wechatSession.getCurrentLogin();
			if(loginModel!=null){
				qrCustomer=(Customer)loginModel.get(AresManageContainer.customer_account_info);
				model.addAttribute("wechatLoginModel", loginModel);
			
				/*查找现在这个人下的推荐人有几个*/
				int inviteSum=customerService.queryInviteSum(loginModel.getUserId());
				model.addAttribute("inviteSum", inviteSum);
				
				sceneCode=String.valueOf(qrCustomer.getUserIdentity());
			}
		}else{
			/*当带了邀请码的时候，通过shareCode来查询这是谁的邀请码*/
			qrCustomer=customerService.queryModelByUserIdentity(Integer.parseInt(sceneCode));
		}	
		model.addAttribute("qrCustomer", qrCustomer);
		model.addAttribute("userIdentity", qrCustomer.getUserIdentity());
		String qrUrl=customerQrcodeUtil.getQrcodeUrl(qrCustomer.getId(), qrCustomer.getLevel(), sceneCode);
		model.addAttribute("qrUrl", qrUrl);
		
		return view(shareCodeQrViewName);
	}
	
	@WechatAuthPassport
	@ResponseBody
	@RequestMapping(value = shareSignatureViewName, method = { RequestMethod.GET,RequestMethod.POST },produces="text/plain;charset=utf-8")
	public String shareSignature(Model model,String href,String shareCode){
		Map<String,Object> resultMap=new HashMap<String,Object>();
		
		WechatLoginModel loginModel=wechatSession.getCurrentLogin();
		if(loginModel!=null){
			Customer customer=(Customer)loginModel.get(AresManageContainer.customer_account_info);
			resultMap.put("loginModel", loginModel);
			resultMap.put("customer", customer);
		}else{
			if(!StringUtils.isEmpty(shareCode)){
				Customer customer=customerService.queryModelByUserIdentity(Integer.parseInt(shareCode));
				resultMap.put("customer", customer);
			}
		}
		
		WxMpService wxMpService=WechatManager.getInstance().getWxMpService();
		try {
			WxJsapiSignature jsapiSignature=wxMpService.createJsapiSignature(href);
			resultMap.put("jsapiSignature", jsapiSignature);
		} catch (WxErrorException e) {
			e.printStackTrace();
		}
		return JsonUtils.toJson(resultMap);
	}
	
	@RequestMapping(value = myTeamViewName, method = { RequestMethod.GET })
	public String myTeam(Model model){
		WechatLoginModel loginModel=wechatSession.getCurrentLogin();
		model.addAttribute("loginModel", loginModel);
		return view(myTeamViewName);
	}
	
	@RequestMapping(value = teamContentViewNameString, method = { RequestMethod.GET,RequestMethod.POST})
	public String teamContent(Model model){
		WechatLoginModel loginModel=wechatSession.getCurrentLogin();
		model.addAttribute("loginModel", loginModel);
		
		int oneTeamShareCount=customerService.queryOneTeamShareCount(loginModel.getUserId());
		int twoTeamShareCount=customerService.queryTwoTeamShareCount(loginModel.getUserId());
		
		model.addAttribute("oneTeamShareCount", oneTeamShareCount);
		model.addAttribute("twoTeamShareCount", twoTeamShareCount);
		
		return view(teamContentViewNameString);
	}
	
	@RequestMapping(value = teamShareViewName, method = { RequestMethod.GET })
	public String teamShare(Model model,String category,String id){
		List<TeamShareCustomer> teamShareCustomers=null;
		
		if("one".equals(category)){
			teamShareCustomers=customerService.queryOneTeamShare(id);
		}else if("two".equals(category)){
			teamShareCustomers=customerService.queryTwoTeamShare(id);
		}
		
		model.addAttribute("teamShareCustomers", teamShareCustomers);
		return view(teamShareViewName);
	}
	
	
	@RequestMapping(value = searchTeamViewName, method = { RequestMethod.GET,RequestMethod.POST})
	public String searchTeam(Model model,String searchContent){
		WechatLoginModel loginModel=wechatSession.getCurrentLogin();
		Customer customer=(Customer)loginModel.get(AresManageContainer.customer_account_info);
		model.addAttribute("customer", customer);
		
		List<TeamShareCustomer>teamShareCustomers = customerService.queryWechatSearch(searchContent, customer.getId());
		
		model.addAttribute("teamShareCustomers", teamShareCustomers);
		
		return view(teamShareViewName);
	}
	
	@RequestMapping(value = currentTeamShareViewName, method = { RequestMethod.GET })
	public String currentTeamShare(Model model,String id,String username){
		List<Customer> customers=customerService.queryCurrentChildCustomer(id);
		model.addAttribute("customers", customers);
		model.addAttribute("username", username);
		
		return view(currentTeamShareViewName);
	}
	
	@ResponseBody
	@RequestMapping(value = getCustomerInfoViewName, method = { RequestMethod.GET,RequestMethod.POST },produces="text/plain;charset=utf-8")
	public String getCustomerInfo(Model model){
		WechatLoginModel loginModel=wechatSession.getCurrentLogin();
		Customer customer=(Customer)loginModel.get(AresManageContainer.customer_account_info);
		
		return JsonUtils.toJson(customer);
	}
		
	private void updateLoginModel(){
		//重新更新一下customer_account_info
		WechatLoginModel loginModel = wechatSession.getCurrentLogin();
		Customer customer=customerService.queryModelByOpenId(loginModel.getOpenId());
		loginModel.setUserId(customer.getId());
		loginModel.put(AresManageContainer.customer_account_info, customer);
	}
	
	@RequestMapping(value = personDetailedViewName, method = { RequestMethod.GET,RequestMethod.POST })
	public String personDetailed(Model model,Customer changecustomer){
				
		WechatLoginModel loginModel=wechatSession.getCurrentLogin();
		
		changecustomer.setId(loginModel.getUserId());		

		if(customerService.updateCustDetail(changecustomer)){
			wechatSession.setCurrentLogin(loginModel);
			updateLoginModel();
		}
		
		Customer customer=customerService.queryModel(loginModel.getUserId()); 
			
		String isMaker = "noMaker";
		
		if(customer.getLevel().equals("vip")||customer.getLevel().equals("visitor")){
			isMaker = "notMaker";
		}else {	
			if(customer.getUpdateRegionDate()==null){
				customer.setUpdateRegionDate(DateUtils.getCurrent());
			}
			WithdrawParam withdrawParam1 =withdrawParamService.queryModelByHelpCode("regionIntervalTime");
			WithdrawParam withdrawParam2 =withdrawParamService.queryModelByHelpCode("regionUpdateTime");
			int month = withdrawParam1.getParam();
			int day = withdrawParam2.getParam();
			Date nowDate = DateUtils.getCurrent();
			Date changeDate =AddMonthUtil.addMonth(month, customer.getUpdateRegionDate());
			Date overDate = DateUtils.addDay(day, changeDate);	
				
				
			if (DateUtils.compare_date(nowDate, changeDate)==1 && DateUtils.compare_date(nowDate, overDate)==-1) {				
				isMaker = "yesMaker";				
			}else {
				isMaker = "noMaker";
			}
			model.addAttribute("month", month);
		}
		model.addAttribute("loginModel", loginModel);
		model.addAttribute("customer", customer);
		model.addAttribute("isMaker",isMaker);
		return view(personDetailedViewName);
	}
	
	@RequestMapping(value = realNameViewName, method = { RequestMethod.GET,RequestMethod.POST })
	public String realName(Model model){
		return view(realNameViewName);
	}
	
	
	@RequestMapping(value = torealNameViewName, method = { RequestMethod.GET,RequestMethod.POST })
	@ResponseBody
	public String torealName(Model model,String custRealName,String custIDCard){
		
		String strUrl = "http://op.juhe.cn/idcard/query";
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("key",realNameUtil.APPKEY);
		params.put("realname", custRealName);
		params.put("idcard", custIDCard);
		
		String method = "GET";
		try {
			 String rs = realNameUtil.net(strUrl, params, method);			 
			 HashMap<String, Object> rsMap = JsonUtils.convert2Map(rs);	
			 if(!StringUtils.isEmpty(rsMap.get("result"))){
				 
				 @SuppressWarnings("unchecked")
				HashMap<String, Object> result = (HashMap<String, Object>)rsMap.get("result");
				 
				 if((Integer)result.get("res")==1){
						
					 WechatLoginModel loginModel=wechatSession.getCurrentLogin();
					 //改变用户表的实名认证状态
					 if(customerService.updateCustomerState(loginModel.getUserId(),YesOrNo.yes,custRealName,CusttomerIDtype.idCard, custIDCard)){return "true";}								
				 }
			 }		 					 
			 System.out.println("实名认证错误码=="+rsMap.get("error_code"));
			 System.out.println("实名认证错误说明=="+rsMap.get("reason"));
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		return "false";
				
	}
}
